﻿using System;
using System.Collections.Generic;
using System.Linq;
using Yamfinder.Data;

namespace Yamfinder.Service
{
    public class DataTypeService : IDataTypeService
    {
        private readonly IDataDictonaryRepository _dataDictonaryRepository;

        public DataTypeService(IDataDictonaryRepository dataDictonaryRepository)
        {
            _dataDictonaryRepository = dataDictonaryRepository;
        }

        public IList<DataDictonaryEntry> Search(DataTypeSearchCriteria search)
        {
            return ApplySearchCriteria(search).ToList();
        }

        public PaginatedList<DataDictonaryEntry> Search(DataTypeSearchCriteria search, int pageIndex, int pageSize)
        {
            return new PaginatedList<DataDictonaryEntry>(ApplySearchCriteria(search), pageIndex, pageSize);
        }

        public void ChangeIsRequired(string fieldName, bool value)
        {
            var entry = _dataDictonaryRepository.Get(fieldName);

            entry.IsRequired = value;

            _dataDictonaryRepository.Save(entry);
        }

        public void ChangeIsDisplayed(string fieldName, bool value)
        {
            var entry = _dataDictonaryRepository.Get(fieldName);

            entry.IsDisplayed = value;

            _dataDictonaryRepository.Save(entry);
        }

        public void Add(string fieldName, string type, bool isRequired, bool isDisplayed)
        {
            _dataDictonaryRepository.Insert(new DataDictonaryEntry()
                                                {
                                                    IsDisplayed = isDisplayed,
                                                    IsRequired = isRequired,
                                                    Name = fieldName,
                                                    Type = type
                                                });
        }

        private IQueryable<DataDictonaryEntry> ApplySearchCriteria(DataTypeSearchCriteria searchCriteria)
        {
            var entries = _dataDictonaryRepository.Query();

            if (!string.IsNullOrEmpty(searchCriteria.Name))
            {
                //apply string search
                entries = entries.Where(x => x.Name.Contains(searchCriteria.Name));
            }

            if (!string.IsNullOrEmpty(searchCriteria.Type) && (searchCriteria.Type != "All"))
            {
                //apply type condition
                entries = entries.Where(x => x.Type == searchCriteria.Type);
            }

            if (searchCriteria.OnlyRequired)
            {
                entries = entries.Where(x => x.IsRequired);
            }

            return entries;
        }
    }
}